package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户实现类
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private JwtProperties jwtProperties;

    @Override
    public UserLoginVO wxLogin(UserLoginDTO userLoginDTO) {
        // 1.调用微信接口，获取openid
        String openId = getOpenId(userLoginDTO.getCode());
        log.info("[微信登录，获取openid] openid:{}",openId);
        // 2.存数据库(相当于插入用户)
        // 正常逻辑：根据openid,先去数据库查询，如果没有就插入数据库
        User user  = userMapper.selectByOpenId(openId);
        if (user == null){
            user = new User();
            user.setOpenid(openId);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }
        // 3.生成token
        Map<String,Object> payLoad = new HashMap<>();
        // 把数据库用户的Id,存入载荷中
        payLoad.put(JwtClaimsConstant.USER_ID,user.getId());

        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(), payLoad);

        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setId(user.getId());
        userLoginVO.setOpenid(openId);
        userLoginVO.setToken(token);
        return userLoginVO;
    }

    @Resource
    private WeChatProperties weChatProperties;

    private String getOpenId(String code) {
        // 直接使用我们封装的工具类连接微信
        // String url ="https://api.weixin.qq.com/sns/jscode2session?appid=wx67d4ca0312578351&secret=e1658af5e55a1ab7c5816111c3713441&grant_type=authorization_code&js_code="+code;
        Map<String,String> param = new HashMap<>();
        param.put("appid",weChatProperties.getAppid());
        param.put("secret",weChatProperties.getSecret());
        param.put("grant_type","authorization_code");
        param.put("js_code",code);

        String jsonData = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", param);
        // {"":"","":"}，从JSON中获取openId
        JSONObject jsonObject = JSON.parseObject(jsonData);
        return jsonObject.get("openid").toString();
    }
}
